import csv
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, HttpResponse
from .models import DeviceInfo
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from .forms import CreateDeviceInfoForm, CreateAdminInfoForm, UserRegisterForm
from django.contrib import messages
from django.db.models import Q
from django.contrib.auth.models import User


@login_required(login_url='/login/')
def device_list(request):
    devices_info = DeviceInfo.objects.all()
    paginator = Paginator(devices_info, 10)  # Show 25 contacts per page.
    page_number = request.GET.get('page', 1)

    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        # 如果请求的页码不是整数，返回第一页。
        page_obj = paginator.page(1)
    except EmptyPage:
        # 如果请求的页码超出页数，返回最后一页。
        page_obj = paginator.page(paginator.num_pages)

    current_page = int(page_number)
    device_verbose_names = {field.name: field.verbose_name for field in DeviceInfo._meta.fields}
    return render(request, 'device_list.html',
                  {'devices_info': devices_info, 'page_obj': page_obj, 'current_page': current_page,
                   "device_verbose_names": device_verbose_names})


@login_required(login_url='/login/')
def device_detail(request, pk):
    devices_info = DeviceInfo.objects.get(id=pk)
    return render(request, '../templates/device_detail.html', {'devices_info': devices_info})


def device_register(request):
    if request.method == 'POST':
        print("hello")
        form = CreateDeviceInfoForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '新建成功！')
            return redirect('device:device_list')
    else:
        form = CreateDeviceInfoForm()
    return render(request, '../templates/device_create.html', {'form': form})


@login_required(login_url='/login/')
def device_updata(request, pk):
    devices_info = DeviceInfo.objects.get(id=pk)
    if request.method == "POST":
        form = CreateDeviceInfoForm(request.POST, instance=devices_info)
        if form.is_valid():
            form.save()
            messages.success(request, '更新成功!')
            return redirect('device:device_list')
        else:
            return redirect('device:device_list')
    #            return HttpResponse("update successfully")
    else:
        form = CreateDeviceInfoForm(instance=devices_info)
    return render(request, '../templates/device_updata.html', {'form': form, 'device_id': pk})


@login_required(login_url='/login/')
def device_delete(request, pk):
    devices_info = DeviceInfo.objects.get(id=pk)
    if request.method == "POST":
        devices_info.delete()
        # messages.success(request,'%s 已删除' % user_info.name)
        messages.success(request, '删除成功')
        return redirect('device:device_list')
    else:
        return render(request, '../templates/device_delete.html', {'devices_info': devices_info})


@login_required(login_url='/login/')
def device_search(request):
    if request.method == 'GET':
        keyword = request.GET.get('search')
        if keyword:
            devices_info = DeviceInfo.objects.filter(
                Q(device_name__contains=keyword) | Q(device_id__contains=keyword) | Q(
                    device_addr__contains=keyword) | Q(
                    device_model__contains=keyword))
            if devices_info.exists():
                paginator = Paginator(devices_info, 10)  # Show 25 contacts per page.
                page_number = request.GET.get('page', 1)
                page_obj = paginator.get_page(page_number)
                current_page = int(page_number)
                device_verbose_names = {field.name: field.verbose_name for field in DeviceInfo._meta.fields}
                return render(request, 'device_search.html',
                              {'devices_info': devices_info, 'page_obj': page_obj, 'current_page': current_page,
                               'keyword': keyword,
                               'device_verbose_names': device_verbose_names})
            else:
                messages.success(request, '查询不到!')
            return redirect('device:device_list')
        else:
            messages.success(request, '查询不到!')
        return redirect('device:device_list')

    else:
        messages.success(request, '查询不到!')
    return redirect('device:device_list')


@login_required(login_url='/login/')
def export_to_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename={}.csv'.format(request.user.username)
    if 'Windows' in request.headers.get('User-Agent'):
        response.charset = 'utf-8-sig'
    devices_info = DeviceInfo.objects.all().order_by('id')
    writer = csv.writer(response)
    writer.writerow(["设备名称", "设备编号", "设备地址", "设备型号"])
    for device_info in devices_info:
        writer.writerow(
            [device_info.device_name, device_info.device_id, device_info.device_model, device_info.device_addr])
    return response


@login_required(login_url='/login/')
def admin_list(request):
    admin_users = User.objects.all()
    paginator = Paginator(admin_users, 10)  # Show 25 contacts per page.
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    current_page = int(page_number)
    return render(request, 'admin_list.html', {'admin_users': page_obj, 'current_page': current_page})


@login_required(login_url='/login/')
def admin_updata(request, pk):
    admin_info = User.objects.get(id=pk)
    if request.method == "POST":
        form = CreateAdminInfoForm(request.POST, instance=admin_info)
        if form.is_valid():
            form.save()
            messages.success(request, '更新成功!')
            return redirect('device:device_list')
        else:
            return redirect('device:device_list')
    else:
        form = CreateAdminInfoForm(instance=admin_info)
    return render(request, 'admin_updata.html', {'form': form, 'admin_id': pk})


@login_required(login_url='/login/')
def admin_delete(request, pk):
    admin_info = User.objects.get(id=pk)
    if request.method == "POST":
        admin_info.delete()
        messages.success(request, '删除成功')
        return redirect('device:admin_list')
    else:
        return render(request, 'admin_delete.html', {'admin_info': admin_info})


@login_required(login_url='/login/')
def admin_register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '注册成功！')
            HttpResponse(request, "Created device successfully")
            return redirect('device:admin_list')
    else:
        form = UserRegisterForm()
    return render(request, 'admin_register.html', {'form': form})
